package com.huffman.smart_picture.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.huffman.smart_picture.config.CosClientConfig;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.CIObject;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.qcloud.cos.model.ciModel.persistence.ProcessResults;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * @author DengLin
 * @date 2025/1/18 14:37
 * @description: 文件上传模板
 */
@Slf4j
public abstract class PictureUploadTemplate {
    protected static final long ONE_M = 1024 * 1024;

    protected static final List<String> ALLOW_FILE_TYPE = Arrays.asList("jpg", "png", "jpeg", "webp");

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private CosManager cosManager;

    /**
     * @param inputSource
     * @param uploadPathPrefix
     * @param isAdmin          管理员可忽略文件大小上传
     * @return
     */
    public final PictureUploadDto uploadPicture(Object inputSource, String uploadPathPrefix, boolean isAdmin) {
        // 校验图片是否合法
        validPicture(inputSource, isAdmin);
        //图片上传地址
        String uuid = RandomUtil.randomString(16);
        String originFilename = getOriginFilename(inputSource);
        String uploadFilename = String.format("%s/%s.%s", DateUtil.format(new Date(), "yyyy-MM-dd"), uuid, FileUtil.getSuffix(originFilename));
        String uploadPath = String.format("/%s/%s", uploadPathPrefix, uploadFilename);
        File file = null;
        PictureUploadDto pictureUploadDto = new PictureUploadDto();
        try {
            file = File.createTempFile(uploadPath, null);
            processFile(inputSource, file);
            PutObjectResult putObjectResult = cosManager.putPictureObject(uploadPath, file);
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            int picWidth = imageInfo.getWidth();
            int picHeight = imageInfo.getHeight();
            double picScale = NumberUtil.round(picWidth * 1.0 / picHeight, 2).doubleValue();
            String imageType = imageInfo.getFormat();
//            if (uploadPath.endsWith("0")) {
//                uploadPath = uploadPath.substring(0, uploadPath.length() - 2) + imageType.toLowerCase();
//            }
            pictureUploadDto.setUrl(cosClientConfig.getHost() + "/" + uploadPath);
            pictureUploadDto.setPicColor(imageInfo.getAve());
            pictureUploadDto.setPicName(originFilename);
            pictureUploadDto.setPicSize(FileUtil.size(file));
            pictureUploadDto.setPicWidth(picWidth);
            pictureUploadDto.setPicHeight(picHeight);
            pictureUploadDto.setPicScale(picScale);
            pictureUploadDto.setPicFormat(imageType);
            ProcessResults processResults = putObjectResult.getCiUploadResult().getProcessResults();
            List<CIObject> processResultList = processResults.getObjectList();
            if (!CollectionUtils.isEmpty(processResultList)) {
                // 压缩图片
                CIObject compressCiObject = processResultList.get(0);
                pictureUploadDto.setCompressUrl(cosClientConfig.getHost() + "/" + compressCiObject.getKey());
                // 缩略图片
                CIObject thumbnailCiObject = processResultList.get(1);
                pictureUploadDto.setThumbnailUrl(cosClientConfig.getHost() + "/" + thumbnailCiObject.getKey());
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (file != null) {
                if (!file.delete()) {
                    log.error("delete file error,filePath={}", file.getAbsoluteFile());
                }
            }
        }
        return pictureUploadDto;
    }

    /**
     * 图片删除
     *
     * @param key
     */
    public final void deletePicture(String key) {
        cosManager.deleteObject(key);
    }

    protected abstract void validPicture(Object inputSource, boolean ignoreSize);

    protected abstract String getOriginFilename(Object inputSource);

    protected abstract void processFile(Object inputSource, File file) throws Exception;
}
